<template>
  <div class="chart-wrapper" :style="{ width: width, height: height }">
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'

// Props定义
const props = defineProps({
  option: {
    type: Object,
    required: true
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  },
  loading: {
    type: Boolean,
    default: false
  },
  theme: {
    type: String,
    default: 'light'
  }
})

// Emits定义
const emit = defineEmits(['chart-click', 'chart-ready'])

// 响应式数据
const chartRef = ref(null)
let chartInstance = null

// 计算属性 - 图表配置
const chartOption = computed(() => {
  const baseOption = {
    backgroundColor: 'transparent',
    textStyle: {
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'
    },
    ...props.option
  }

  // 根据主题调整颜色
  if (props.theme === 'dark') {
    baseOption.textStyle.color = '#fff'
  }

  return baseOption
})

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  chartInstance = echarts.init(chartRef.value)
  chartInstance.setOption(chartOption.value)

  // 绑定点击事件
  chartInstance.on('click', (params) => {
    emit('chart-click', params)
  })

  emit('chart-ready', chartInstance)
}

// 更新图表
const updateChart = () => {
  if (chartInstance) {
    chartInstance.setOption(chartOption.value, true)
  }
}

// 刷新图表
const refreshChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 获取图表实例
const getChartInstance = () => {
  return chartInstance
}

// 监听配置变化
watch(() => props.option, () => {
  updateChart()
}, { deep: true })

// 监听加载状态
watch(() => props.loading, (newVal) => {
  if (chartInstance) {
    if (newVal) {
      chartInstance.showLoading()
    } else {
      chartInstance.hideLoading()
    }
  }
})

// 生命周期
onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 暴露方法
defineExpose({
  getChartInstance,
  refreshChart
})
</script>

<style scoped>
.chart-wrapper {
  position: relative;
  overflow: hidden;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>
